package com.fzdy.dataplatform.dao.impl;

import com.fzdy.dataplatform.core.common.TimeStampTool;
import com.fzdy.dataplatform.core.dao.impl.BaseDaoImpl;
import com.fzdy.dataplatform.dao.DeviceConfigDao;
import com.fzdy.dataplatform.entity.DeviceConfig;
import org.hibernate.Criteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Repository
public class DeviceConfigDaoImpl extends BaseDaoImpl<DeviceConfig> implements DeviceConfigDao {


    @Override
    public List<DeviceConfig> findByExampleEq(String createdate, DeviceConfig example, int pageNo, int pageSize) {
        Criteria criteria = this.getSession().createCriteria(this.clazz).add(Example.create(example));
        Date startDate=startDate(createdate);
        Date endDate=endDate(createdate);
        criteria.add(Restrictions.between("createdate",startDate,endDate));
//        criteria.add(Restrictions.like("createdate",createdate, MatchMode.START));
        List list = this.createPageOrder(criteria, pageNo, pageSize, Order.desc("id")).list();
        return list;
    }

    @Override
    public long countByExampleEq(String createdate, DeviceConfig example) {
        Criteria criteria = this.getSession().createCriteria(this.clazz).add(Example.create(example));
        Date startDate=startDate(createdate);
        Date endDate=endDate(createdate);
        criteria.add(Restrictions.between("createdate",startDate,endDate));
//        criteria.add(Restrictions.like("createdate",createdate, MatchMode.START));
        return this.countCriteria(criteria);
    }


    private Date startDate(String date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(TimeStampTool.StringToDate("yyyy-MM", date));
        //获取年
        int year = calendar.get(Calendar.YEAR);
        //获取月份，0表示1月份
        int month = calendar.get(Calendar.MONTH) + 1;
        //获取本月最小天数
        int first = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
        //获取本月最大天数
        String begin = year + "-" + month + "-" + first+" 00:00:00";
        return TimeStampTool.StringToDate("yyyy-MM-dd", begin);
    }

    private Date endDate(String date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(TimeStampTool.StringToDate("yyyy-MM", date));
        //获取年
        int year = calendar.get(Calendar.YEAR);
        //获取月份，0表示1月份
        int month = calendar.get(Calendar.MONTH) + 1;
        //获取本月最大天数
        int last = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        String end = year + "-" + month + "-" + last+" 23:59:59";
        return TimeStampTool.StringToDate("yyyy-MM-dd HH:mm:ss", end);
    }

}
